"""
数据库的连接与关闭

对数据库写操作会默认开启事务，
如果数据表支持事务需要commit提交才能生效，
如果数据表不支持事务则execute执行语句后立即生效
"""
import pymysql

# 参数字典
kwargs = {
    "host":"localhost",
    "port": 3306,
    "user": "root",
    "password": "root",
    "database": "stu",
    "charset": "utf8"
}

# 连接数据库
db = pymysql.connect(**kwargs)

# 生成游标：执行sql操作数据，得到操作结果的对象
cur = db.cursor()
try:
    sql = "select name,score from class where score>%s"
    cur.execute(sql,[70])

    # one = cur.fetchone()
    # print(one)
    #
    # many = cur.fetchmany(2)
    # print(many)

    results = cur.fetchall()
    print(results)
except Exception as e:
    print(e)
    db.rollback()
else:
    db.commit() # 提交事务

# 关闭
cur.close()
db.close()